<template>
	<div class="page-wrapper">	
		<div style="height:8%; padding-bottom:var(--mPadding);">
			<div class="flex-btn large" @click="info = { visible:true, forEdit:false } ">
				<img :src="Icon" />新建模板
			</div>
		</div>
		<div style="height:92%;">
			<TableWrapper :style="{ height:'100%' }" :controls="controls" :pageInfo="pageInfo" :sourceData="tableData" :column="column" :total="total"  @search="handleSearch" />
		</div>
		<!-- 新建巡检对象模板 弹窗 -->
		<TemplateAddDrawer v-model:info="info" :labelList="labelList" :meterTypeList="meterTypeList" @refresh="fetchTplList" />
	</div> 
</template>

<script setup>
	import { reactive, onMounted, watch, computed, ref, h } from 'vue';
	import { useRouter, useRoute } from 'vue-router';
	import { useGlobalStore } from '@/stores/global';
	import { getTplList, getLabelList, getMeterTypeList, delTpl } from '@/api/tpl.js';
	import { ElMessage, ElPopconfirm, ElInput  } from 'element-plus'
	import TableWrapper from '@/components/TableWrapper/index.vue';
	import TemplateAddDrawer from './TemplateAddDrawer.vue';
	import ConfirmDel from '@/components/ConfirmDel.vue';
	import Icon from '@/assets/icon-add.png';

	const router = useRouter();
	const route = useRoute();
	const tableData = ref([]);
	const labelList = ref([]);
	const meterTypeList = ref([]);
	const meterTypeMaps = ref({});
	const labelMaps = ref({});
	const pageInfo = reactive({ page:1, pageSize:10 });
	const total = ref(0);
	const controls = ref([
		{ type:'input', paramKey:'codeOrName', placeholder:'输入编号或名称查询' },
		{ type:'select', paramKey:'labelId', payload:[], placeholder:'请选择标签' },
	]);
	const controlUpdate = computed(()=>{
		return labelList.value.length ? true : false;
	});
	watch(controlUpdate, ()=>{
		controls.value = [
			{ type:'input', paramKey:'codeOrName', placeholder:'输入编号或名称查询' },
			{ type:'select', paramKey:'labelId', payload:labelList.value, labelName:'labelName', labelKey:'labelId',  placeholder:'请选择标签' },
		];
	})
	const checkWayMaps = {
		0:'全部检查',
		1:'抽查',
		2:'循环抽查'
	}
	const info = ref({ visible:false, forEdit:false });
    const column = [
        { label:'编号', width:'10%', prop:'templateCode' }, 
        { label:'名称', width:'20%', prop:'templateName' },
		{ label:'标签', width:'20%', hasTpl:true, render:row=>{
			return { com:h('div', null, row.labelId === 1 ? `${labelMaps.value[row.labelId]}${ meterTypeMaps.value[row.equipmentType] ? '(' + meterTypeMaps.value[row.equipmentType] + ')' :''  }` : labelMaps.value[row.labelId] ) } } 
		},
        { label:'检查方式', width:'20%', hasTpl:true, render:row=>{ return { com:h('div', null, row.checkWay === 0 ? checkWayMaps[row.checkWay] : `${checkWayMaps[row.checkWay]}(抽查比例 ${row.checkValue}%)` ) }} },
        { label:'操作', width:'20%', hasTpl:true, render:(row)=>{
            return {
				com:h('div', { class:'action-container' }, [
                	h('div', { onClick:()=>{ router.push({ path:'/templateManagement/inspectionItems', query:{ code:row.templateCode, page:pageInfo.page } }) }}, [h('i', { class:'ri-settings-line' }), h('span', null, '巡检项管理')]),
                	h('div', { onClick:()=>{ info.value = { visible:true, forEdit:true, row } }}, [h('i', { class:"ri-edit-line" }), h('span', null, '编辑')]),
					h(ConfirmDel, { info:`确定要删除${row.templateName}吗？`,  onConfirm:()=>{ handleDelete(row.templateCode) }} )
            	])
			}
        }
		}
    ]; 	

	const handleSearch = (optional)=>{
		// 调用请求接口
		fetchTplList({ ...optional });
	}
	const handleDelete = (code)=>{
		delTpl({ templateCode:code })
		.then(res=>{
			if ( res.data.code === 200 ) {
				ElMessage({
					type:'success',
					message:'删除模板成功！' 
				});
				fetchTplList();
			}
		})
	}
	const fetchTplList = (params)=>{
		// 实际的axios请求;
		params = params || {};
		let realParams = { page:pageInfo.page, pageSize:pageInfo.pageSize };
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		getTplList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				tableData.value = res.data.data;
				total.value = res.data.total;
			}
		})
	};
	const fetchLabelList = ()=>{
		getLabelList()
		.then(res=>{
			if ( res.data.code === 200 ){
				let response = res.data.data;
				let obj = {};
				if ( response && response.length ) {
					response.forEach(i=>{
						obj[i.labelId] = i.labelName;
					})
				}				
				labelList.value = res.data.data;
				labelMaps.value = obj;

			}
		})
	}
	// 请求设备类型列表
	const fetchMeterTypeList = ()=>{
        getMeterTypeList()
        .then(res=>{
            if ( res.data.code === 200 ) {
				let response = res.data.data;
				let obj = {};
				if ( response && response.length ) {
					response.forEach(i=>{
						obj[i.typeId] = i.typeName;
					})
				}	
                meterTypeList.value = res.data.data;
				meterTypeMaps.value = obj;
            }
        })
    }
	onMounted(()=>{
		if ( route.query.page ) {
			pageInfo.page = Number(route.query.page);
		} 
		fetchTplList();
		fetchLabelList();
		fetchMeterTypeList();
	})
	
</script>
